package org.nlp2rdf.navigator.benchmark;

import com.hp.hpl.jena.rdf.model.Resource;

import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * Created by Claus Stadler
 * Date: Oct 13, 2010
 * Time: 12:58:27 AM
 */
public class KFoldCollection<E>
    extends AbstractCollection<KFoldContext<E>>
{
    private List<Sample<E>> kFolds;
    private long randomSeed;

    public KFoldCollection(int numFolds, int foldSize, Sample<E> pool, Random random)
    {
        this.kFolds = BenchmarkUtils.createStratifiedKFolds(numFolds, foldSize, pool.getPositives(), pool.getNegatives(), random);
        this.randomSeed = random.nextLong();
    }


    public static <E> KFoldCollection create(int numFolds, int foldSize, Sample<E> pool, Random random)
    {
        return new KFoldCollection(numFolds, foldSize, pool, random);
    }

    /**
     *
     * @param numFolds
     * @param pool All positives will be distributed among the folds, afterwards, it will be filled up with negatives
     * @param ratio
     * @param random
     * @param <E>
     * @return
     */
    public static <E> KFoldCollection create(int numFolds, Sample<E> pool, float ratio, Random random)
    {
        int numPositivesPerFold = Math.round(pool.getPositives().size() / (float)numFolds);
        int foldSize = Math.round(numPositivesPerFold / ratio);

        return create(numFolds, foldSize, pool, random); 
    }

    @Override
    public Iterator<KFoldContext<E>> iterator() {
        return new KFoldIterator<E>(kFolds, new Random(randomSeed));
    }

    @Override
    public int size() {
        return kFolds.size();
    }
}

